import Vue from "vue";
import Router from "vue-router";
import routes from "./router";
// eslint-disable-next-line no-unused-vars
import store from "@/store/index";
import { Notify } from "vant";
import { NEED_LOGIN } from "@/router/router";

Vue.use(Router);
const router = new Router({
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return {x: 0, y: 0};
    }
  }
});
// 视图切换动画逻辑
const setTitle = title => {
  window.document.title = title || "";
};
// eslint-disable-next-line no-unused-vars
//to代表要去的页面，from代表去之前的页面 next表示是否同意去to页面
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  if (to.matched.some(page => page.meta.loginAuth)) {
    if (token) {
      to.meta && setTitle(to.meta.title);
      next();
    } else {
      next({
        path: NEED_LOGIN
      });
    }
  } else {
    if (to.path === NEED_LOGIN) {
      if (token) {
        Notify("请勿异常操作");
        next(false);
      } else {
        to.meta && setTitle(to.meta.title);
        next();
      }
    } else {
      to.meta && setTitle(to.meta.title);
      next();
    }
  }
});
router.afterEach(() => {
});
export default router;
